<template>
    <div>
        <!-- 添加竞赛表单 -->
        <el-form :model="newCompetition" label-width="120px">
            <el-form-item label="标题">
                <el-input v-model="newCompetition.title" placeholder="请输入竞赛标题"></el-input>
            </el-form-item>
            <el-form-item label="主办方">
                <el-input v-model="newCompetition.organizer" placeholder="请输入主办方"></el-input>
            </el-form-item>
            <el-form-item label="报名开始时间">
                <el-date-picker
                    v-model="newCompetition.registrationStartTime"
                    type="datetime"
                    placeholder="选择报名开始时间"
                ></el-date-picker>
            </el-form-item>
            <el-form-item label="报名结束时间">
                <el-date-picker
                    v-model="newCompetition.registrationEndTime"
                    type="datetime"
                    placeholder="选择报名结束时间"
                ></el-date-picker>
            </el-form-item>
            <el-form-item label="比赛开始时间">
                <el-date-picker
                    v-model="newCompetition.competitionStartTime"
                    type="datetime"
                    placeholder="选择比赛开始时间"
                ></el-date-picker>
            </el-form-item>
            <el-form-item label="比赛结束时间">
                <el-date-picker
                    v-model="newCompetition.competitionEndTime"
                    type="datetime"
                    placeholder="选择比赛结束时间"
                ></el-date-picker>
            </el-form-item>
            <el-form-item label="类别">
                <!-- 直接显示固定值 "竞赛" -->
                <span>竞赛</span>
            </el-form-item>
            <el-form-item label="具体下分类别">
                <!-- 下分类别下拉框 -->
                <el-select v-model="newCompetition.subCategory" placeholder="请选择具体下分类别">
                    <el-option
                        v-for="option in subCategoryOptions"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="添加人工号">
                <el-input v-model="newCompetition.employeeNumber" disabled></el-input>
            </el-form-item>
            <el-form-item label="图片">
                <!-- 图片上传组件 -->
                <el-upload
                    :before-upload="handleBeforeUpload"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                    :show-file-list="false"
                >
                    <el-button type="primary">上传图片</el-button>
                </el-upload>
                <!-- 显示当前图片 -->
                <img v-if="imageUrl" :src="imageUrl" width="200" height="200" alt="竞赛图片" />
            </el-form-item>
            <el-form-item label="网站地址">
                <el-input v-model="newCompetition.websiteUrl" placeholder="请输入网站地址"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="addCompetition">添加竞赛</el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import service from "@/utils/request";
import { ElMessage } from 'element-plus';

// 新竞赛数据
const newCompetition = ref({
    title: '',
    organizer: '',
    registrationStartTime: '',
    registrationEndTime: '',
    competitionStartTime: '',
    competitionEndTime: '',
    category: '竞赛', // 直接固定为 "竞赛"
    subCategory: '', // 具体下分类别
    employeeNumber: localStorage.getItem('employeeNumber') || '', // 从 localStorage 获取工号
    photoUrl: '', // 图片路径
    websiteUrl: '' // 新增：网站地址
});

// 暂存的的图片 URL
const imageUrl = ref('');

// 下分类别选项（固定为 "竞赛" 类别下的数据）
const subCategoryOptions = ref([
    { label: '文体类', value: '文体类' },
    { label: '商科类', value: '商科类' },
    { label: '理科类', value: '理科类' },
    { label: '综合类', value: '综合类' },
    { label: '工科类', value: '工科类' }
]);



/**
 * 图片上传前的处理
 * @param {File} file - 上传的文件
 * @returns {boolean} 是否阻止默认上传行为
 */
const handleBeforeUpload = (file) => {
    const formData = new FormData();
    formData.append('file', file);

    service.post('/upload/image', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
        .then(response => {
            handleUploadSuccess(response.data);
        })
        .catch(error => {
            handleUploadError(error);
        });

    return false; // 阻止默认上传行为
};

/**
 * 图片上传成功
 * @param {string} response - 图片路径
 */
const handleUploadSuccess = (response) => {
    if (response) {
        newCompetition.value.photoUrl = response; // 保存图片路径
        // imageUrl.value = newCompetition.value.photoUrl; // 显示图片
        loadImage(response); // 加载图片
        ElMessage.success('图片上传成功');
    }
};
/**
 * 加载图片
 * @param {string} imagePath - 图片路径
 */
const loadImage = (imagePath) => {
    console.log('加载图片:', imagePath);

    service.get(`/images/${imagePath}`, {
        responseType: 'blob'
    })
        .then(response => {
            imageUrl.value = URL.createObjectURL(response.data);
            console.log('加载图片 URL:', imageUrl.value);
        })
        .catch(error => {
            console.error('图片加载失败', error);
            ElMessage.error('图片加载失败，请重试');
        });
};
/**
 * 图片上传失败
 * @param {Error} error - 错误信息
 */
const handleUploadError = (error) => {
    console.error('图片上传失败', error);
    ElMessage.error('图片上传失败，请重试');
};

/**
 * 添加竞赛
 */
const addCompetition = async () => {
    try {
        // 发送添加竞赛请求
        await service.post('/admin/competition/save', newCompetition.value);
        ElMessage.success('竞赛添加成功');
        resetForm(); // 重置表单
    } catch (error) {
        console.error('添加竞赛失败', error);
        ElMessage.error('竞赛添加失败');
    }
};

/**
 * 重置表单
 */
const resetForm = () => {
    newCompetition.value = {
        title: '',
        organizer: '',
        registrationStartTime: '',
        registrationEndTime: '',
        competitionStartTime: '',
        competitionEndTime: '',
        category: '竞赛',
        subCategory: '',
        employeeNumber: '',
        photoUrl: '',
        websiteUrl: '' // 重置网站地址
    };
    imageUrl.value = ''; // 清空图片显示
};
</script>

<style scoped>
/* 自定义样式 */
</style>